package com.apache.publish.mapper.Impl;

import com.apache.publish.mapper.PublishMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据层
 */
@Slf4j //加入日志
@Repository
public class PublishMapperImpl implements PublishMapper {

    //加入ES客户端
    @Autowired
    RestHighLevelClient esClient;

    private String indexNamePrefix = "gmall_dau_info_";

    //查询总数
    public Long SearchDauTodal(String td) {
        String indexName = indexNamePrefix + td;
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //不要明细
        searchSourceBuilder.size(0);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            long dauTodals = searchResponse.getHits().getTotalHits().value;
            return dauTodals;
        } catch (ElasticsearchStatusException ese) {
            if (ese.status() == RestStatus.NOT_FOUND) {
                log.warn(indexName + "不存在....");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("查询ES失败");
        }
        return 0L;
    }

    //查询分时明细
    public Map<String, Long> searchDauHr(String td) {
        HashMap<String, Long> dauHr = new HashMap<>();

        String indexName = indexNamePrefix + td;
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //不要明细
        searchSourceBuilder.size(0);
        //聚合
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("groupbyhr").field("hr.keyword").size(24);
        searchSourceBuilder.aggregation(termsAggregationBuilder);

        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            ParsedTerms parsedTerms = aggregations.get("groupbyhr");
            List<? extends Terms.Bucket> buckets = parsedTerms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String hr = bucket.getKeyAsString();
                long hrTodal = bucket.getDocCount();
                dauHr.put(hr, hrTodal);
            }

            return dauHr;
        } catch (ElasticsearchStatusException ese) {
            if (ese.status() == RestStatus.NOT_FOUND) {
                log.warn(indexName + "不存在....");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("查询ES失败");
        }
        return dauHr;
    }

    @Override
    public Map<String, Object> searchDau(String td) {
        //测试ES查询总数
        Map<String, Object> dauResults = new HashMap<>();

        Long dauTodal = SearchDauTodal(td);
        dauResults.put("dauTodal", dauTodal);

        //测试ES分时明细
        //今日分时明细
        Map<String, Long> dauTd = searchDauHr(td);
        dauResults.put("dauTd", dauTd);

        //昨日分时明细
        LocalDate tdLd = LocalDate.parse(td);
        LocalDate ydLd = tdLd.minusDays(1);
        Map<String, Long> dauYd = searchDauHr(ydLd.toString());
        dauResults.put("dauYd", dauYd);


        //测试一个死的
        //Map<String, Object> dauResults = new HashMap<>();
        //dauResults.put("dauTotal", 123);

//        //今日分时明细
//        Map<String, Long> dauTd = new HashMap<>();
//        dauTd.put("12", 90L);
//        dauTd.put("13", 33L);
//        dauTd.put("17", 133L);
//
//        dauResults.put("dauTd", dauTd);
//
//        //作日分时明细
//        Map<String, Long> dauYd = new HashMap<>();
//        dauYd.put("11", 232L);
//        dauYd.put("15", 45L);
//        dauYd.put("18", 76L);
//
//        dauResults.put("dauYd", dauYd);

        return dauResults;
    }

    public static void main(String[] args) {
        //测试日期
        String td = "2022-11-16";
        LocalDate tdLd = LocalDate.parse(td);
        LocalDate ydLd = tdLd.minusDays(1);
        System.out.println(ydLd.toString()); //2022-11-15
    }
}
